/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mxgraph.examples.swing;

/**
 *
 * @author somesh
 */
//package com.mxgraph.examples.swing;
import java.awt.Color;

//import org.shortpasta.icmp2.IcmpPingUtil;
//import org.shortpasta.icmp2.IcmpPingRequest;
//import org.shortpasta.icmp2.IcmpPingResponse;
//import org.shortpasta.icmp2.util.ArgUtil;

import com.mxgraph.examples.swing.editor.ArrayListofVisibleItem;
import com.mxgraph.examples.swing.editor.DatabaseConnectivity;
import com.mxgraph.model.mxCell;
import com.mxgraph.model.mxGeometry;
import com.mxgraph.model.mxGraphModel;
import com.mxgraph.model.mxICell;
import com.mxgraph.model.mxIGraphModel;

import com.mxgraph.util.mxConstants;
import com.mxgraph.util.mxPoint;
import com.mxgraph.util.mxUtils;
import com.mxgraph.view.mxGraph;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
//import com.mxgraph.view.
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * ShortPasta Foundation http://www.shortpasta.org Copyright 2009 and beyond,
 * Sal Ingrilli at the ShortPasta Software Foundation
 * <p/>
 * This is free software; you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License version 3 as published by the
 * Free Software Foundation as long as: 1. You credit the original author
 * somewhere within your product or website 2. The credit is easily reachable
 * and not burried deep 3. Your end-user can easily see it 4. You register your
 * name (optional) and company/group/org name (required) at
 * http://www.shortpasta.org 5. You do all of the above within 4 weeks of
 * integrating this software 6. You contribute feedback, fixes, and requests for
 * features
 * <p/>
 * If/when you derive a commercial gain from using this software please donate
 * at http://www.shortpasta.org
 * <p/>
 * If prefer or require, contact the author specified above to: 1. Release you
 * from the above requirements 2. Acquire a commercial license 3. Purchase a
 * support contract 4. Request a different license 5. Anything else
 * <p/>
 * This software is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE, similarly to how this is described in the GNU
 * Lesser General Public License.
 * <p/>
 * User: Sal Ingrilli Date: May 23, 2014 Time: 6:43:43 PM
 */
public class DeviceCheckingThread implements Runnable {

    GraphEditor editor;
    String ipAddress;
    private static String OS = System.getProperty("os.name").toLowerCase();

    public DeviceCheckingThread(GraphEditor editor) {
        this.editor = editor;
    }

    /**
     * The Java interface
     *
     * To test: cd
     * c:\dev\shortpasta\trunk\icmp2\output\publish\shortpasta-icmp2\lib java
     * -cp * org.shortpasta.icmp2.tool.Ping www.google.com
     *
     * @param args
     */
    private static boolean isWindows() {
        return (OS.indexOf("win") >= 0);
    }

    private static boolean isUnix() {
        return (OS.indexOf("nux") >= 0);
    }

    @Override
    public void run() {
        Statement stmt = DatabaseConnectivity.generateStatement();
//    stmt = 
        String sqlForSwitchIP = ("SELECT ip FROM packetfence_manuallyAddswitch_info");
        String sqlForAnotherSwitchIP = ("SELECT ip FROM packetfence_switch_info");
        String sqlForServerIP = ("SELECT ip FROM packetfence_server_info");
        String sqlForPrinterIP = ("SELECT ip FROM packetfence_printer_info");
        String sqlForRouterIP = ("SELECT ips FROM packetfence_router_info");
        String sqlForFirewallIP = ("SELECT ips FROM packetfence_firewall_info");
        mxGraph graph = editor.getGraphComponent().getGraph();
        String optionNumberOfPingRequest = "-c";
        ArrayList<String> pingOutPut = new ArrayList<String>();
        ArrayList<String> switchAnotherIP = new ArrayList<String>();
        ArrayList<String> serverIP = new ArrayList<String>();
        ArrayList<String> printerIP = new ArrayList<String>();
        ArrayList<String> routerIP = new ArrayList<String>();
        ArrayList<String> firewallIP = new ArrayList<String>();
        //graph.getd
        //mxIGraph graphI = (mxIGraph)editor.getGraphComponent().getGraph();
        //String[] switchIP = null;
        //String[] switchAnotherIP = null ;
        //String[] serverIP = null;
        //String[] printerIP = null;
        //String[] routerIP = null;
        //String[] firewallIP = null;
        if (isWindows()) {
            //Runtime.getRuntime().exec(new String[]
            //    {"cmd", "/k", "start", "cmd", "/c", "\"ping " + ipAddress+ " & pause\""});
            optionNumberOfPingRequest = "-n";
        } else if (isUnix()) {
            optionNumberOfPingRequest = "-c";

        }
        //try {
        while (true) {
           // System.out.println("PingThread is Alive");
            int ipCounter = 0;

            try {
                //System.out.println("111111111111");
                // if ((!(switchAnotherIP.size() == 0))) {
                mxIGraphModel model = graph.getModel();
                //model.get
                int childCount = model.getChildCount(graph.getDefaultParent());

                for (int i = 0; i < childCount; i++) {
                    Object cell = model.getChildAt(graph.getDefaultParent(), i);
                    //((mxCell)cell).ge
                    mxCell myCell = ((mxCell) cell);
                    if (!(((mxCell) cell).getId().contains("Edge"))) {

                        String DisplayDeviceIP = ((mxCell) cell).getId();
                        String[] Splitter = DisplayDeviceIP.split("_");
////////////////////////////////////////////////////////////////////////////////
////                                    Switch                            //////
////////////////////////////////////////////////////////////////////////////////                          
                        if (Splitter[0].contains("Switch") || Splitter[0].contains("Printer")) {
                            StringBuffer output = new StringBuffer();
                            Process p;
                           // System.out.println("ping " + optionNumberOfPingRequest + " 1 " + Splitter[1]);
                            p = Runtime.getRuntime().exec("ping " + optionNumberOfPingRequest + " 1 " + Splitter[1]);
                            p.waitFor();
                            BufferedReader reader =
                                    new BufferedReader(new InputStreamReader(p.getInputStream()));
                            String lastLine = "", line = "";
                            int lineCounter = 0;
                            while ((line = reader.readLine()) != null) {
                                pingOutPut.add(line);
                                lineCounter++;
                                output.append(line + "\n");
                                lastLine = line;
                            }
                            //output.
                            //System.out.println("pingOutPut.size()-2" + (pingOutPut.size() - 2));
                           // System.out.println("pingOutPut.get(pingOutPut.size()-1)):" + pingOutPut.get(pingOutPut.size() - 1));
                            if (pingOutPut.get(pingOutPut.size() - 2).contains("100% packet loss") || pingOutPut.get(pingOutPut.size() - 2).contains("errors")) {
                                //graph.refresh();
                                ArrayListofVisibleItem.deviceRTTHashMap.put(Splitter[1], pingOutPut.get(pingOutPut.size() - 2));
                                ArrayListofVisibleItem.deviceReachability.put(Splitter[1], "CRITICAL");
                               // System.out.println(mxConstants.STYLE_OPACITY);
                                if (Splitter[0].contains("Switch")) {
                                    myCell.setStyle("image;image=/com/mxgraph/examples/swing/images/SwitchIconRed.png;" + mxConstants.STYLE_OPACITY + "=50f;" + mxConstants.STYLE_FONTCOLOR + "=" + mxUtils.hexString(Color.RED));
                                } else {
                                    myCell.setStyle("image;image=/com/mxgraph/examples/swing/images/PrinterRed.png;" + mxConstants.STYLE_OPACITY + "=50f;" + mxConstants.STYLE_FONTCOLOR + "=" + mxUtils.hexString(Color.RED));
                                }
                                //System.out.println("myCell.getStyle():" + myCell.getStyle());
                                graph.refresh();
                                //Thread.sleep(5000);
                            } else {
                                ArrayListofVisibleItem.deviceRTTHashMap.put(Splitter[1], pingOutPut.get(pingOutPut.size() - 1));
                                ArrayListofVisibleItem.deviceReachability.put(Splitter[1], "OK");
                                if (myCell.getStyle().contains("=50f")) {
                                    if (Splitter[0].contains("Switch")) {
                                        myCell.setStyle("image;image=/com/mxgraph/examples/swing/images/SwitchIcon.png");
                                    } else {
                                        myCell.setStyle("image;image=/com/mxgraph/examples/swing/images/PrinterGreen.png");
                                    }
                                }
                                graph.refresh();
                               // System.out.println(myCell.getStyle() + "myCell.getStyle()");
                            }
                        } ////////////////////////////////////////////////////////////////////////////////
                        ////                                    Server                            //////
                        ////////////////////////////////////////////////////////////////////////////////                            
                        else if (Splitter[0].contains("Server")) {
                            //ArrayListofVisibleItem.deviceRTTHashMap.put(Splitter[1], pingOutPut.get(pingOutPut.size() - 2));
                            //ArrayListofVisibleItem.deviceReachability.put(Splitter[1], "CRITICAL");

                            StringBuffer output = new StringBuffer();
                            Process p;
                           // System.out.println("ping " + optionNumberOfPingRequest + " 1 " + Splitter[1]);
                            p = Runtime.getRuntime().exec("ping " + optionNumberOfPingRequest + " 1 " + Splitter[1]);
                            p.waitFor();
                            BufferedReader reader =
                                    new BufferedReader(new InputStreamReader(p.getInputStream()));
                            String lastLine = "", line = "";
                            int lineCounter = 0;
                            while ((line = reader.readLine()) != null) {
                                pingOutPut.add(line);
                                lineCounter++;
                                output.append(line + "\n");
                                lastLine = line;
                            }
                            if (pingOutPut.get(pingOutPut.size() - 2).contains("100% packet loss") || pingOutPut.get(pingOutPut.size() - 2).contains("errors")) {
                                ArrayListofVisibleItem.deviceRTTHashMap.put(Splitter[1], pingOutPut.get(pingOutPut.size() - 2));
                                ArrayListofVisibleItem.deviceReachability.put(Splitter[1], "CRITICAL");

                                //graph.refresh();
                               // System.out.println(mxConstants.STYLE_OPACITY);
                                myCell.setStyle("image;image=/com/mxgraph/examples/swing/images/ServerRed.png;" + mxConstants.STYLE_OPACITY + "=50f;" + mxConstants.STYLE_FONTCOLOR + "=" + mxUtils.hexString(Color.RED));
                                //System.out.println("myCell.getStyle():" + myCell.getStyle());
                                graph.refresh();
                                //Thread.sleep(5000);
                            } else {
                                ArrayListofVisibleItem.deviceRTTHashMap.put(Splitter[1], pingOutPut.get(pingOutPut.size() - 1));
                                ArrayListofVisibleItem.deviceReachability.put(Splitter[1], "OK");
                                int flagForPort = 0;
                                int counterOpenPort = 0;
                                String[] portArray = null;
                                try {
                                    String sqlForServerPort = ("SELECT * FROM packetfence_server_info  WHERE ip LIKE '" + Splitter[1] + "'");
                                    // Try to create the Socket on the port.
                                    // If you fail to create the Socket.
                                    // Socket is not open

                                    ResultSet rs = stmt.executeQuery(sqlForServerPort);
                                    ipCounter = 0;
                                    
                                    while (rs.next()) {
                                        String temp = rs.getString("portnumber");
                                        portArray =temp.split(",");
                                        ipCounter++;
                                    }
                                    int temp = portArray.length;//
                                    String openPort = "";
                                    String closePort = "";
                                    
                                    for (int j = 0; j < portArray.length; j++) {
                                        try {  //int portNumber = (Integer)portArray[j];
                                            //System.out.println("portArray[j]:"+portArray[j]);
                                            Socket socket = new Socket();
                                            SocketAddress endpoint = new InetSocketAddress( Splitter[1], Integer.parseInt(portArray[j]));
                                            //Socket socket = new Socket(Splitter[1], Integer.parseInt(portArray[j]));
                                            socket.connect(endpoint, 1000);
                                            String message = portArray[j] + " is open in " + Splitter[1];
                                            //System.out.println(message);
                                            socket.close();
                                            openPort += portArray[j] + ",";
                                            counterOpenPort++;
                                            //ArrayListofVisibleItem.serverOpenPort.put(Splitter[1], portArray[j]);
                                            //   }
                                        } catch (IOException e) {
                                            // If fail to create Socket,
                                            // The port is not open
                                            flagForPort++;
                                            closePort += portArray[j] + ",";
                                            
                                            //System.out.println("Close Port:"+portArray[j]);
                                        }
                                    }
                                    ArrayListofVisibleItem.serverOpenPort.put(Splitter[1], openPort);
                                    ArrayListofVisibleItem.serverClosedPort.put(Splitter[1], closePort);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                if(flagForPort>0){
                                myCell.setStyle("image;image=/com/mxgraph/examples/swing/images/ServerYellow.png");
                                }
                                if (myCell.getStyle().contains("=50f")|| counterOpenPort== portArray.length) {
//myCell.
                                    myCell.setStyle("image;image=/com/mxgraph/examples/swing/images/ServerGreen.png");
                                }
                                graph.refresh();
                                //System.out.println(myCell.getStyle() + "myCell.getStyle()");
                            }
////////////////////////////////////////////////////////////////////////////////
////                              Router & Firewall                       //////
////////////////////////////////////////////////////////////////////////////////                            

                        } else if (Splitter[0].contains("Router") || Splitter[0].contains("Firewall")) {

                            String IPs[] = Splitter[1].split(",");
                            int numberOfLiveIPs = 0;
                            InetAddress inet;
                            for (int j = 0; j < IPs.length; j++) {

                                StringBuffer output = new StringBuffer();
                                Process p;
                               // System.out.println("ping " + optionNumberOfPingRequest + " 1 " + Splitter[1]);
                                p = Runtime.getRuntime().exec("ping " + optionNumberOfPingRequest + " 1 " + Splitter[1]);
                                p.waitFor();
                                BufferedReader reader =
                                        new BufferedReader(new InputStreamReader(p.getInputStream()));
                                String lastLine = "", line = "";
                                int lineCounter = 0;
                                while ((line = reader.readLine()) != null) {
                                    pingOutPut.add(line);
                                    lineCounter++;
                                    output.append(line + "\n");
                                    lastLine = line;
                                }
                                if (pingOutPut.get(pingOutPut.size() - 2).contains("100% packet loss") || pingOutPut.get(pingOutPut.size() - 2).contains("errors")) {
                                    ArrayListofVisibleItem.deviceRTTHashMap.put(Splitter[1], pingOutPut.get(pingOutPut.size() - 2));
                                    ArrayListofVisibleItem.deviceReachability.put(Splitter[1], "CRITICAL");

                                    //graph.refresh();
                                   // System.out.println(mxConstants.STYLE_OPACITY);
                                    if (Splitter[0].contains("Router")) {
                                        myCell.setStyle("image;image=/com/mxgraph/examples/swing/images/RouterRed.png;" + mxConstants.STYLE_OPACITY + "=50f;" + mxConstants.STYLE_FONTCOLOR + "=" + mxUtils.hexString(Color.RED));
                                    } else {
                                        myCell.setStyle("image;image=/com/mxgraph/examples/swing/images/FirewallIcon.png;" + mxConstants.STYLE_OPACITY + "=50f;" + mxConstants.STYLE_FONTCOLOR + "=" + mxUtils.hexString(Color.RED));
                                    }
                                    //System.out.println("myCell.getStyle():" + myCell.getStyle());
                                    graph.refresh();
                                    //Thread.sleep(5000);
                                } else {
                                    numberOfLiveIPs++;

                                    graph.refresh();
                                    //System.out.println(myCell.getStyle() + "myCell.getStyle()");
                                }

                            }
                            if (numberOfLiveIPs == IPs.length) {
                                ArrayListofVisibleItem.deviceRTTHashMap.put(Splitter[1], pingOutPut.get(pingOutPut.size() - 1));
                                ArrayListofVisibleItem.deviceReachability.put(Splitter[1], "OK");

                                if (myCell.getStyle().contains("=50f")) {
                                    if (Splitter[0].contains("Router")) {
                                        myCell.setStyle("image;image=/com/mxgraph/examples/swing/images/RouterGreen.png");
                                    } else {
                                        myCell.setStyle("image;image=/com/mxgraph/examples/swing/images/FirewallIcon.png");
                                    }
                                }
                            }
                        }

                    }//*/
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                Thread.sleep(5000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    } //catch (final Throwable t) {
    // log
    // t.printStackTrace();
    //}
    //}
    // TODO Auto-generated method stub
}